#include <QtGlobal>
#include "qtts.h"
#include "AudioRender/aiswavfile.h"

#include "aisiflytekagent.h" // SDK by Iflytek, voicecloud.cn

AISIflytekAgent::AISIflytekAgent() : bAgentIsReady(false)
  , bCancelSpeak(false)
{
}

int AISIflytekAgent::initTTSEngine()
{
    // APPID can not change.
#ifdef Q_OS_LINUX
    const char *m_configs = "appid=521d3acc"; // the APPID of jink2005 in linux
#endif
#ifdef Q_OS_WIN
    const char* m_configs = "appid=52071017"; // the APPID of jink2005 in windows
#endif

    int ret = QTTSInit(m_configs);
    if (MSP_SUCCESS == ret)
    {
        bAgentIsReady = true;
    }
    return ret;
}

int AISIflytekAgent::speakText(const char *text)
{
    if (NULL == text)
    {
        return -1;
    }

    const char *param1 = "ssm=1,auf=audio/L16;rate=16000,vcn=xiaoyan,tte=UTF8";
    const char *sessID = NULL;
    int ret = MSP_SUCCESS;
    sessID = QTTSSessionBegin(param1, &ret);
    if (MSP_SUCCESS != ret)
    {
        return ret;
    }

    size_t textLen = strlen(text);
    ret = QTTSTextPut(sessID, text, textLen, NULL);
    if (MSP_SUCCESS != ret)
    {
        QTTSSessionEnd(sessID, "TextPutError");
        return ret;
    }

    char *pAudioData = NULL;
    unsigned int audioLen = 0;
    int synthStatus = MSP_TTS_FLAG_STILL_HAVE_DATA;

    AISWavFile *wavFile = new AISWavFile;
    wavFile->openFile("aisReader.wav", QFile::WriteOnly | QFile::Text);
    while (! bCancelSpeak)
    {
        pAudioData = (char *)QTTSAudioGet(sessID, &audioLen, &synthStatus, &ret);
        if (MSP_SUCCESS != ret)
        {
            break;
        }

        // use the data
        if (NULL != pAudioData && 0 != audioLen)
        {
            wavFile->writeFile(pAudioData, audioLen);
        }

        if (MSP_TTS_FLAG_DATA_END == synthStatus)
        {
            break;
        }
    }
    wavFile->closeFile();
    ret = QTTSSessionEnd(sessID, "Normal");

    return ret;
}

int AISIflytekAgent::uninitTTSEngine()
{
    int ret = MSP_SUCCESS;
    if (bAgentIsReady)
    {
        bAgentIsReady = false;
        ret = QTTSFini();
    }
    return ret;
}
